//
//  CustomerViewController.m
//  KuWoCan
//
//  Created by LiBenCan on 17/9/25.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "CustomerViewController.h"
#import "CustomerCell.h"
#import "ChooseView.h"
#import "BaseMBView.h"
#import "AddCustomerViewController.h"
@interface CustomerViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UIButton *ChooseBTn;
}
@property (nonatomic,strong)UITableView *tableV;
@property (nonatomic,strong)NSArray *titleArr;
@property (nonatomic,strong)ChooseView *chooseView;
@property (nonatomic,strong)BaseMBView *baseBgView;
@property (nonatomic,strong)UIImageView *addImageV;
@property (nonatomic,strong)NSMutableArray *dataArr;//数据
@property (nonatomic,assign)NSInteger pageNumber;//页码

@property (nonatomic,strong)NSString *nameStr;//客户姓名
@property (nonatomic,strong)NSString *personStr;//联系人
@property (nonatomic,strong)NSString *phoneStr;//联系电话
@property (nonatomic,strong)NSString *AdressStr;//地址
@property (nonatomic,assign)BOOL isEdit;//地址
@property (nonatomic,strong)NSMutableDictionary *requestDic;
@end

@implementation CustomerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _pageNumber = 1;
    _isEdit = YES;
    
    _dataArr = [NSMutableArray new];
    self.title = @"客户列表";
    [self addToolBtn];
    [self.view addSubview:self.tableV];
    [self.view addSubview:self.addImageV];
    
    //全部数据
    _requestDic = [[NSMutableDictionary alloc]initWithDictionary:
    @{
      @"user.id":[Singleton shareInstance].userId,
      @"pageNo":[NSString stringWithFormat:@"%ld",_pageNumber],
      @"pageSize":@"10"}];
    [self addMessgeRequest:YES];
}


-(void)addMessgeRequest:(BOOL)isFresh//数据请求
{
    if (_dataArr.count<=0) {
        [SVProgressHUD show];
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [HttpRequest PostrequestUrl:[NSString stringWithFormat:@"%@/jeesite/interface/appClientInfo/findClientInfo",baseUrlMe] Dic:_requestDic completion:^(NSDictionary *responseDic) {
    
            NSLog(@"======%@",responseDic);
               if ([responseDic[@"success"] boolValue] && _pageNumber == [responseDic[@"clientInfoList"][@"pageNo"] integerValue]) {
                   if (isFresh) {
                       [_dataArr removeAllObjects];
                   }
                   NSArray *arr = [[NSArray alloc]initWithArray:responseDic[@"clientInfoList"][@"list"]];
                   for (int i = 0; i<arr.count; i++) {
                       [_dataArr addObject:arr[i]];
                   }
                   self.title = [NSString stringWithFormat:@"客户列表(%@人)",responseDic[@"clientInfoList"][@"count"]];
               }
               dispatch_async(dispatch_get_main_queue(), ^{
                   [SVProgressHUD dismiss];
                   [_tableV.mj_header endRefreshing];
                   [_tableV.mj_footer endRefreshing];
                   [_tableV reloadData];
               });
               
        }];
    });
}


-(UIImageView *)addImageV//添加按钮
{
    if (!_addImageV) {
        _addImageV = [[UIImageView alloc]initWithFrame:CGRectMake(SCREENW-70*screenW_6,SCREENH-64-75*screenW_6, 50*screenW_6, 50*screenW_6)];
        _addImageV.image = [UIImage imageNamed:@"cus_tianjia"];
        _addImageV.userInteractionEnabled = YES;
        UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goAdd)];
        [_addImageV addGestureRecognizer:imageTap];
        
        [_addImageV bringSubviewToFront:self.view];
    }
    return _addImageV;
}
-(void)addToolBtn{//导航栏右边按钮
    
    //筛选按钮
    ChooseBTn = [UIButton buttonWithType:UIButtonTypeCustom];
    ChooseBTn.frame = CGRectMake(0, 0,25,30);
    [ChooseBTn setImage:[UIImage imageNamed:@"shaixuan"] forState:UIControlStateNormal];
    [ChooseBTn addTarget:self action:@selector(chooseTo:) forControlEvents:UIControlEventTouchUpInside];
    
    //管理编辑按钮
    UIButton *EditBTn = [UIButton buttonWithType:UIButtonTypeCustom];
    EditBTn.frame = CGRectMake(0, 0,25,30);
    [EditBTn setImage:[UIImage imageNamed:@"guanli"] forState:UIControlStateNormal];
    [EditBTn addTarget:self action:@selector(EditTo:) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc]initWithCustomView:EditBTn] ,[[UIBarButtonItem alloc]initWithCustomView:ChooseBTn]];
    
}
-(void)chooseTo:(UIButton *)btn//跳转筛选界面
{
    _nameStr = _personStr = _phoneStr = _AdressStr = @"";
    if (!btn.selected) {//显示筛选View
        typeof(self) weakSelf = self;
        _baseBgView = [[BaseMBView alloc]initWithFrame:CGRectMake(0,0, SCREENW, SCREENH)];
        [_baseBgView showView:self];
        _baseBgView.dissBlock = ^(){//蒙板去除的回调
            [UIView animateWithDuration:0.4 animations:^{
                btn.userInteractionEnabled = NO;
                weakSelf.chooseView.frame = CGRectMake(0,-64-300*screenW_6,SCREENW,280*screenW_6);
            } completion:^(BOOL finished) {
                [weakSelf.chooseView removeFromSuperview];
                [weakSelf.baseBgView removeFromSuperview];
                btn.userInteractionEnabled = YES;
                btn.selected = NO;
                [weakSelf.view endEditing:YES];
            }];
        };
        _chooseView = [[ChooseView alloc]initWithFrame:CGRectMake(0,-64-300*screenW_6,SCREENW,280*screenW_6)];
        [_baseBgView addSubview:_chooseView];
        _chooseView.chooseblock = ^(NSInteger chooseNumber,NSString *str)
         {//编辑和点击按钮的回调
             [weakSelf chooseNumber:chooseNumber Content:str];
         };
        [UIView animateWithDuration:0.4 animations:^{
            btn.userInteractionEnabled = NO;
             _chooseView.frame = CGRectMake(0,0,SCREENW,280*screenW_6);
        } completion:^(BOOL finished) {
            btn.userInteractionEnabled = YES;
        }];
      
    }else//移除筛选View
    {
        [UIView animateWithDuration:0.4 animations:^{
            btn.userInteractionEnabled = NO;
            _chooseView.frame = CGRectMake(0,-64-300*screenW_6,SCREENW,280*screenW_6);
        } completion:^(BOOL finished) {
            [_chooseView removeFromSuperview];
            [_baseBgView removeFromSuperview];
            btn.userInteractionEnabled = YES;
        }];
    }
    btn.selected = !btn.selected;
}
-(void)EditTo:(UIButton *)editBtn//编辑
{
    if (_baseBgView) {
        ChooseBTn.selected = NO;
        ChooseBTn.userInteractionEnabled = YES;
        [_chooseView removeFromSuperview];
        [_baseBgView removeFromSuperview];
        [self.view endEditing:YES];
    }
    _isEdit = !_isEdit;
    [_tableV reloadData];
}
-(UITableView *)tableV
{
    if (!_tableV) {
        _tableV = [[UITableView alloc] initWithFrame:CGRectMake(0,0,SCREENW,SCREENH-64) style:UITableViewStyleGrouped];
        _tableV.estimatedRowHeight = 125*screenW_6;
        _tableV.backgroundColor = [UIColor colorWithHexString:@"#EFF0F5"];
        _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableV.showsVerticalScrollIndicator = NO;
        _tableV.delegate = self;
        _tableV.dataSource = self;
        _tableV.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            _pageNumber = 1;
            [self addMessgeRequest:YES];
        }];
        _tableV.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            _pageNumber++;
            [self addMessgeRequest:NO];
        }];
    }
    return _tableV;
}
#pragma Mark TableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.000001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == _dataArr.count-1) {
        return 10*screenW_6;
    }
    return 0.000001;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomerCell"];
    if (!cell)
    {
        cell = [[CustomerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CustomerCell"];
    }
    if (_dataArr.count>0) {
        [cell loadCell];
        [cell setIsNowEdit:_isEdit];
        [cell setDataDic:_dataArr[indexPath.section]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.editLab.tag = cell.deleteLab.tag = indexPath.section;
        UITapGestureRecognizer *editTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(editSelectTap:)];
        [cell.editLab addGestureRecognizer:editTap];
        UITapGestureRecognizer *deleteTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(deleteSelectTap:)];
        [cell.deleteLab  addGestureRecognizer:deleteTap];
    
    }
    return cell;
}
//筛选点击后处理及数据请求
-(void)chooseNumber:(NSInteger)number Content:(NSString *)content
{
    switch (number) {
        case 0://客户姓名
        {
            _nameStr = content;
        }
            break;
        case 1://联系人
        {
            _personStr = content;
        }
            break;
        case 2://联系电话
        {
            _phoneStr = content;
        }
            break;
        case 3://地址
        {
            _AdressStr = content;
        }
            break;
        case 4://重置
        {
            [_chooseView removeFromSuperview];
            [_baseBgView removeFromSuperview];
            [self.view endEditing:YES];
            ChooseBTn.userInteractionEnabled = YES;
            ChooseBTn.selected = NO;
            _pageNumber = 1;
            _requestDic = [[NSMutableDictionary alloc]initWithDictionary:
                           @{
                             @"user.id":[Singleton shareInstance].userId,
                             @"pageNo":[NSString stringWithFormat:@"%ld",_pageNumber],
                             @"pageSize":@"10"}];
            [self addMessgeRequest:YES];
        }
            break;
        case 5://查询
        {
            [_chooseView removeFromSuperview];
            [_baseBgView removeFromSuperview];
            [self.view endEditing:YES];
            ChooseBTn.userInteractionEnabled = YES;
            ChooseBTn.selected = NO;
            _pageNumber = 1;
            _requestDic = [[NSMutableDictionary alloc]initWithDictionary:
                           @{
                             @"user.id":[Singleton shareInstance].userId,
                             @"pageNo":[NSString stringWithFormat:@"%ld",_pageNumber],
                             @"pageSize":@"10"}];
            if ([ToolViewViewController isNotNullStr:_nameStr]) {
                [_requestDic setObject:_nameStr forKey:@"name"];
            }
            if ([ToolViewViewController isNotNullStr:_personStr]) {
                [_requestDic setObject:_personStr forKey:@"clientContacts"];
            }
            if ([ToolViewViewController isNotNullStr:_phoneStr]) {
                [_requestDic setObject:_phoneStr forKey:@"clientPhone"];
            }
            if ([ToolViewViewController isNotNullStr:_AdressStr]) {
                [_requestDic setObject:_AdressStr forKey:@"allAddress"];
            }

            [self addMessgeRequest:YES];
        }
            break;
            
        default:
            break;
    }
}
-(void)goAdd//添加顾客
{
    AddCustomerViewController *addVC = [[AddCustomerViewController alloc]init];
    addVC.isEdit = NO;
    addVC.backBlock = ^(BOOL isFresh,NSDictionary *dic){
        if (isFresh) {//添加后刷新
            [_tableV.mj_header beginRefreshing];
        }
    };
    [self.navigationController pushViewController:addVC animated:YES];
}
-(void)editSelectTap:(UITapGestureRecognizer *)tap//编辑客户
{
    if (_dataArr.count<tap.view.tag+1) {
        return;
    }
    AddCustomerViewController *addVC = [[AddCustomerViewController alloc]init];
    addVC.dataDic = _dataArr[tap.view.tag];
    addVC.isEdit = YES;
    addVC.backBlock = ^(BOOL isFresh,NSDictionary *dic){
        if (!isFresh) {//编辑修改后替换
            [_dataArr replaceObjectAtIndex:tap.view.tag withObject:dic];
            [_tableV reloadData];
        }
    };
    [self.navigationController pushViewController:addVC animated:YES];
}
-(void)deleteSelectTap:(UITapGestureRecognizer *)tap//删除客户
{
    if (_dataArr.count<tap.view.tag+1) {
        return;
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:[NSString stringWithFormat:@"%@/jeesite/interface/appClientInfo/deleteClientInfo",baseUrlMe] Dic:@{@"id":_dataArr[tap.view.tag][@"id"]} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([responseDic[@"success"] boolValue]) {
                    [_dataArr removeObjectAtIndex:tap.view.tag];
                    [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                    [_tableV reloadData];
                }else{
                    [SVProgressHUD showErrorWithStatus:@"删除失败"];
                }

            });
            
        }];
    });
}
@end
